let path = require("path");
let fs = require("fs");
let express = require("express");
let app = express();
//获取表单内容
app.use(express.urlencoded({
    extended: false
}));
// app.use('/static', express.static('static'));


// 登陆功能
app.post("/login", (req, res) => {
    let persons = fs.readFileSync(__dirname + "/persons.json", "utf8");
    // console.log(persons);
    let user = req.body;
    persons = JSON.parse(persons);
    let u = persons.find((item) => {
        return item.username == user.username && item.password == user.password
    })
    if (u) {
        res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
        res.end("登录成功")
    } else {
        res.writeHead(200, { "content-type": "text/html;charset=utf-8" })
        res.end("登录失败")
    }
})

// 定义注册路由
app.post("/reg", (req, res) => {
    let user = req.body;
    let persons = JSON.parse(fs.readFileSync(__dirname + "/persons.json", "utf8"));
    let u = persons.findIndex((item) => {
        return item.username == user.username && item.password == user.password
    })
    if (u == -1) {
        res.writeHead(200, {
            "content-type": "text/html;charset=utf-8"
        });
        persons.push(user);
        persons = JSON.stringify(persons);
        fs.writeFileSync(__dirname + "/persons.json", persons);
        res.end("注册成功")
    } else {
        res.writeHead(200, {
            "content-type": "text/html;charset=utf-8"
        })
        res.end("该用户已存在")
    }

    // res.send(persons);
    // console.log(persons)

})
app.get("/login", (req, res) => {
    let urlpath = path.join(__dirname + "/login.html");
    let data = fs.readFileSync(urlpath);
    res.end(data);
})

app.get("/reg", (req, res) => {
    let urlpath = path.join(__dirname + "/reg.html");
    let data = fs.readFileSync(urlpath);
    res.end(data);
})

app.listen(4000, "127.0.0.1", () => {
    console.log("启动")
})